import multer = require('multer');
import q = require('bluebird');
import fs = require('fs');
import TCPClient from './TCPClient';
import WebConstant from '../common/WebConstant';

export interface UploadResult{
    "success":boolean;
    "msg":string;
}

export default class UploadUtil {
    private static client = new TCPClient();
    public static uploadFile(req: any, res: any, folder: string): q<UploadResult> {
        if(!folder || folder.length <= 0){
            return new q((resolve,reject)=>{
                resolve({"msg":"内部错误，未知用户", "success":false});
            });
        }

        let uploadPath = WebConstant.UPLOAD_PATH+folder;
        let tempPath = uploadPath+"/temp";
        if(uploadPath == tempPath){
            return new q((resolve,reject)=>{
                resolve({"msg":"不能上传到系统临时文件夹", "success":false});
            });
        }
        try{
            if(!fs.existsSync(uploadPath)){
                fs.mkdirSync(uploadPath);            
            }

            //multer插件的原因，只能先上传到temp目录在移动到指定目录
            //因为form提交field比file获得要迟
            
            if(!fs.existsSync(tempPath)){
                fs.mkdirSync(tempPath);            
            }
        }
        catch(ex){
            return new q((resolve,reject)=>{
                resolve({"msg":"内部错误，不能创建目录", "success":false});
            });
        }
        
        let me = this;
        var storage = multer.diskStorage({
            //设置上传后文件路径，uploads文件夹会自动创建。
            destination: function (req, file, cb) {
                cb(null, tempPath);
            },
            //给上传文件重命名，获取添加后缀名
            filename: function (req, file, cb){
                if(!me.checkFileExt(file.originalname)){
                    cb(new Error("该文件类型不允许上传"), "");
                }
                else{
                    cb(null, file.originalname);
                }
                
            }
        });
        //添加配置文件到muler对象。
        var upload = multer({
            storage: storage,
            limits:{
                fileSize:1024 * 1024 * 1000
            }
        });

        return new q((resolve,reject)=>{
            upload.single("file_data")(req, res, function(err:Error){
                if(!req.file){
                    resolve({"msg":"文件不存在，是否重复提交了?", "success":false});
                    return;
                }
                if(err){
                    resolve({"msg":err.message, "success":false});
                }
                else{
                    try{
                        let selectFolder = req.body.selectFolder || "";
                        let finalPath = uploadPath + "/"+ selectFolder+"/";
                        fs.copyFileSync(req.file.path, finalPath+req.file.originalname);
                        if(req.file.originalname.endsWith(".zip")){
                            me.notifyTask(finalPath+req.file.originalname, finalPath);
                        }
                        fs.unlinkSync(req.file.path);
                        //fs.rmdirSync(tempPath);
                        
                        resolve({"msg":"", "success":true});
                    }
                    catch(ex){
                        console.log(ex.message);
                        resolve({"msg":"Unkown Error", "success":false});
                    }
                }
            });
        });
        
    }

    private static checkFileExt(filename:string):boolean{
        let arrowExt = [".png", ".gif", ".jpg", ".zip"];

        for(let i = 0; i < arrowExt.length; i++){
            if(arrowExt[i] == filename.substr(filename.length - 4)){
                return true;
            }
        }
        return false;
    }
    //通知任务处理服务器
    private static notifyTask(filename:string, dir:string):void{
        console.log("请求解压", filename);
        let msgObj = {"file":filename, "dir":dir};
        this.client.sendMessage(JSON.stringify(msgObj));
    }
    public static connectTask():void{
        this.client.connectTo("127.0.0.1", 5701, (msg:string)=>{
            console.log("from task server:",msg);
        });
    }
}